package com.yxtbd.travel.travelvm.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.yxtbd.travel.travelvm.ui.NetProgressDialog

/**
 * description ： BaseVMActivity
 *
 * author : taodq
 * date : 2020/3/27 14:55
 */
abstract class BaseVMActivity<VM : BaseViewModle> : AppCompatActivity(), LifecycleObserver {

    lateinit var mViewModel: VM

    open fun providerVMClass(): Class<VM>? = null

    open val progressBar by lazy {
        NetProgressDialog(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initVM()
        startObserve()
        setContentView(getLayoutResId())
        initView()
    }

    abstract fun getLayoutResId(): Int
    abstract fun initView()

    private fun initVM() {
        providerVMClass()?.let {
            mViewModel = ViewModelProvider(this).get(it)
            mViewModel.let { lifecycle::addObserver }
        }
    }

    open fun startObserve() {
        mViewModel.mException.observe(this, Observer { it?.let { onError(it) } })
    }

    open fun onError(e: Throwable) {}

    override fun onDestroy() {
        mViewModel.let {
            lifecycle.removeObserver(it)
        }
        super.onDestroy()
    }
}
